package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vo.AdUserVO;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {


    @Transactional
    @Override
    public ResponseResult login(AdUserDTO dto) {
        //参数判断
        if (StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"参数缺失");
        }
        //根据用户名查询信息
        AdUser adUser = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        //判断用户状态
        if (adUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        if (AdminConstants.USER_STATUS_ALLOW != adUser.getStatus()) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户状态异常，请联系管理员");
        }

        //进行密码判断
        String password = adUser.getPassword();
        String salt = adUser.getSalt();
        String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        if (!inputPwd.equals(password)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
        }
        //修改登录时间
        adUser.setCreatedTime(new Date());
        this.updateById(adUser);
        //颁发token令牌
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        //返回user信息，注意使用的是AdUserVo
        //以token为key存入集合中
        HashMap map = new HashMap<>();
        AdUserVO adUserVO = new AdUserVO();
        //使用工具类快速复制封装类
        try {
            BeanUtils.copyProperties(adUser,adUserVO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("token",token);
        map.put("user",adUserVO);
        return ResponseResult.okResult(map);
    }
}
